package com.v1.video.view;

import java.util.ArrayList;
import java.util.List;

import com.v1.video.R;
import com.v1.video.activity.BaseActivity;
import com.v1.video.domain.ActionItem;
import com.v1.video.util.Utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

/**
 * @author yangyu 功能描述：标题按钮上的弹窗（继承自PopupWindow）
 */
public class PopupMenuControl extends PopupWindow {

	private Context mContext;

	// 列表弹窗的间隔
	protected final int LIST_PADDING = 10;

	// 实例化一个矩形
	private Rect mRect = new Rect();

	// 坐标的位置（x、y）
	private final int[] mLocation = new int[2];

	// 屏幕的宽度和高度
	private int mScreenWidth, mScreenHeight;

	// 判断是否需要添加或更新列表子类项
	private boolean mIsDirty;

	// 位置不在中心
	private int popupGravity = Gravity.NO_GRAVITY;

	// 弹窗子类项选中时的监听
	private OnItemOnClickListener mItemOnClickListener;

	private OnWindowCloseListener mWindowCloseListener;

	private boolean isSystem = true;// 是否系统自动关闭

	// 定义列表对象
	private ListView mListView;

	// 定义弹窗子类项列表
	private ArrayList<ActionItem> mActionItems = new ArrayList<ActionItem>();

	private BaseAdapter mAdapter;

	public void refresh() {
		if (mAdapter != null)
			mAdapter.notifyDataSetChanged();
	}

	public PopupMenuControl(Context context) {
		// 设置布局的参数
		this(context, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	}

	public PopupMenuControl(Context context, int width, int height) {
		this.mContext = context;

		// 设置可以获得焦点
		setFocusable(true);
		// 设置弹窗内可点击
		setTouchable(true);
		// 设置弹窗外可点击
		setOutsideTouchable(true);

		// 获得屏幕的宽度和高度
		mScreenWidth = Utils.getScreenWidth(mContext);
		mScreenHeight = Utils.getScreenHeight(mContext);

		// 设置弹窗的宽度和高度
		setWidth(width);
		setHeight(height);

		setBackgroundDrawable(new BitmapDrawable());

		// 设置弹窗的布局界面
		setContentView(LayoutInflater.from(mContext).inflate(
				R.layout.popup_menu_bg, null));

		initUI();
	}

	/**
	 * 初始化弹窗列表
	 */
	private void initUI() {
		mListView = (ListView) getContentView().findViewById(R.id.title_list);

		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,
					long arg3) {
				// 点击子类项后，弹窗消失
				ActionItem item = mActionItems.get(index);
				if (mItemOnClickListener != null && !item.mIsLine){
					isSystem = false;
					dismiss();
					mItemOnClickListener.onItemClick(mActionItems.get(index),
							index);
				}
			}
		});
	}
	

	/**
	 * 显示弹窗列表界面
	 */
	public void show(View view) {
		// 获得点击屏幕的位置坐标
		view.getLocationOnScreen(mLocation);

		// 设置矩形的大小
		mRect.set(mLocation[0], mLocation[1], mLocation[0] + view.getWidth(),
				mLocation[1] + view.getHeight());

		// 判断是否需要添加或更新列表子类项
		if (mIsDirty) {
			populateActions();
		}

		/*// 显示弹窗的位置
		
		 * showAtLocation(view, popupGravity, LIST_PADDING - (getWidth() / 2),
		 * mRect.bottom);
		 
		switch (view.getId()) {
		case R.id.hotBtnLay:
			this.showAsDropDown(view,
					-(view.getWidth() + Utils.dip2px(mContext, 7)) / 2, 0);
			break;
		case R.id.myBtnLay:
			this.showAsDropDown(view,
					(-view.getWidth() + Utils.dip2px(mContext, 8)) / 2, 0);
			break;
		default:
			this.showAsDropDown(view, -view.getWidth() / 2, 0);
			break;
		}*/
		//this.showAsDropDown(view, -view.getWidth() / 2, 0);
		//LIST_PADDING + (getWidth())
		WindowManager.LayoutParams lp = ((BaseActivity) mContext).getWindow()
				.getAttributes();
		lp.alpha = 0.5f;
		((BaseActivity) mContext).getWindow().setAttributes(lp);
		int width=(int)mContext.getResources().getDimension(R.dimen.main_menu_upload_padding);
		showAtLocation(view, popupGravity, mScreenWidth-this.getWidth()-width/2, mRect.bottom+5);
//		showAtLocation(view, popupGravity, mScreenWidth, mRect.bottom+5); 
	}

	/**
	 * 隐藏对话框
	 */
	@Override
	public void dismiss() {
		WindowManager.LayoutParams lp = ((BaseActivity) mContext).getWindow()
				.getAttributes();
		lp.alpha = 1.0f;
		((BaseActivity) mContext).getWindow().setAttributes(lp);
		if (isSystem && mWindowCloseListener != null) {
			isSystem = true;
			mWindowCloseListener.onDimiss(this);
		}
		isSystem = true;
		super.dismiss();
	}

	/**
	 * 设置弹窗列表子项
	 */
	private void populateActions() {
		mIsDirty = false;
		mAdapter = new BaseAdapter() {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				PlaceHolder ph = null;
				if (convertView == null) {
					convertView = LayoutInflater.from(mContext).inflate(
							R.layout.popup_window_item, null);
					ph = new PlaceHolder();
					ph.parentLay = convertView.findViewById(R.id.parentLay);
					ph.iconImg =  (ImageView)convertView.findViewById(R.id.iconImg);
					ph.title = (TextView) convertView
							.findViewById(R.id.popupMenuTitle);
					ph.moreLine = (TextView) convertView
							.findViewById(R.id.moreline);
					ph.rebPoint = (ImageView) convertView
							.findViewById(R.id.rebPoint);
					convertView.setTag(ph);
				} else {
					ph = (PlaceHolder) convertView.getTag();
				}

				ActionItem item = mActionItems.get(position);

				if (item.mIsLine) {
					ph.title.setVisibility(View.GONE);
					ph.moreLine.setVisibility(View.VISIBLE);
					ph.moreLine.setText("---更多-----------");
					ph.parentLay.setBackgroundResource(Color.TRANSPARENT);
					ph.iconImg.setVisibility(View.INVISIBLE);
				} else {
					if(item.mDrawable!=null){
						ph.iconImg.setVisibility(View.VISIBLE);
						ph.iconImg.setImageDrawable(item.mDrawable);
					}else{
						ph.iconImg.setVisibility(View.INVISIBLE);
					}
					ph.title.setVisibility(View.VISIBLE);
					ph.title.setText(item.mTitle);
					ph.moreLine.setVisibility(View.GONE);
					/*if (item.mIsSelected) {
						ph.parentLay
								.setBackgroundResource(R.drawable.v1_main_menu_bg_selected);
						ph.title.setTextColor(mContext.getResources().getColor(
								R.color.title_alpha_blue));
					} else {
						ph.parentLay
								.setBackgroundResource(R.drawable.popup_menu_title_list_selector);
						ColorStateList csl = (ColorStateList) mContext
								.getResources()
								.getColorStateList(
										R.color.popup_menu_title_textcolor_list_selector);
						if (csl != null) {
							ph.title.setTextColor(csl);
						}
					}
					if (item.mIsShowRedPoint) {
						ph.rebPoint.setVisibility(View.VISIBLE);
					} else {
						ph.rebPoint.setVisibility(View.GONE);
					}*/
				}
				// 设置文本文字
				// 设置文字与图标的间隔
				// textView.setCompoundDrawablePadding(10);
				// 设置在文字的左边放一个图标
				// textView.setCompoundDrawablesWithIntrinsicBounds(item.mDrawable,
				// null , null, null);

				return convertView;
			}

			@Override
			public long getItemId(int position) {
				return position;
			}

			@Override
			public Object getItem(int position) {
				return mActionItems.get(position);
			}

			@Override
			public int getCount() {
				return mActionItems.size();
			}
		};
		// 设置列表的适配器
		mListView.setAdapter(mAdapter);
	}

	/**
	 * 添加子类项
	 */
	public void addAction(ActionItem action) {
		if (action != null) {
			mActionItems.add(action);
			mIsDirty = true;
		}
	}

	/**
	 * 清除子类项
	 */
	public void cleanAction() {
		if (mActionItems.isEmpty()) {
			mActionItems.clear();
			mIsDirty = true;
		}
	}

	/**
	 * 根据位置得到子类项
	 */
	public ActionItem getAction(int position) {
		if (position < 0 || position > mActionItems.size())
			return null;
		return mActionItems.get(position);
	}

	/**
	 * 返回所有item项目
	 * 
	 * @return
	 */
	public List<ActionItem> getAllActions() {
		return this.mActionItems;
	}

	/**
	 * 设置监听事件
	 */
	public void setItemOnClickListener(
			OnItemOnClickListener onItemOnClickListener) {
		this.mItemOnClickListener = onItemOnClickListener;
	}

	/**
	 * 设置关闭对话框监听事件
	 * 
	 * @param mWindowCloseListener
	 */
	public void setWindowCloseListener(
			OnWindowCloseListener mWindowCloseListener) {
		this.mWindowCloseListener = mWindowCloseListener;
	}

	/**
	 * @author yangyu 功能描述：弹窗子类项按钮监听事件
	 */
	public static interface OnItemOnClickListener {
		public void onItemClick(ActionItem item, int position);
	}

	/**
	 * 关闭对话框监听事件
	 * 
	 * @author shenjin
	 * 
	 */
	public static interface OnWindowCloseListener {
		public void onDimiss(PopupMenuControl pc);
	}

	private class PlaceHolder {
		private View parentLay;
		private ImageView iconImg;
		private TextView title;
		private TextView moreLine;
		private ImageView rebPoint;
	}
}
